package com.woniuxy.project.listener;

import com.woniuxy.project.util.ProjectExpireUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    // 配置监听哪个频道
    private static final Topic KEYEVENT_EXPIRED_TOPIC = new PatternTopic("__keyevent@0__:expired");

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Resource
    private ProjectExpireUtil projectExpireUtil;

    @Override
    protected void doRegister(RedisMessageListenerContainer listenerContainer) {
        // 频道可以是多个，多个传list
        listenerContainer.addMessageListener(this,KEYEVENT_EXPIRED_TOPIC);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用获取失效的key
        String expiredKey = message.toString();
//        log.debug(expiredKey);
        // 判断
        //  如果是project_start_则开始招标
        if (expiredKey.startsWith("project_start_")){
            //  获得订单编号
            String pno = expiredKey.split("_")[2];
            //  异步处理
            projectExpireUtil.handleStart(pno);
        }
        //  如果是project_end_则停止招标
        if (expiredKey.startsWith("project_end_")){
            //  获取秒杀的id
            String pno = expiredKey.split("_")[2];
            projectExpireUtil.handleEnd(pno);
        }
        //  如果是project_overdue_则查看还款情况
        if (expiredKey.startsWith("project_overdue_")){
            //  获取秒杀的id
            String pno = expiredKey.split("_")[2];
            projectExpireUtil.handleOverdue(pno);
        }
    }
}
